const jwt = require("jsonwebtoken");

/**
 * 生成 token
 * @param payload 负载
 * @param exp 过期时间，单位秒
 * @returns token
 */
export const createToken = (payload: any, exp: number) => {
    return jwt.sign(payload, "ikun", {
        expiresIn: exp
        // algorithm: "RS256" rs256 为非对称加密，默认为 HS256 对称加密
    });
};

/**
 * 验证 token 是否有效
 * @param authorization 请求头中的 token 字符串
 * @returns {boolean} true: token 有效，false 无效
 */
export const verifyToken = (authorization: string) => {
    const token = authorization.replace("Bearer ", "");
    try {
        // const payload = jwt.verify(token, "ikun", {
        //     algorithms: ["RS256"]
        // });
        const payload = jwt.verify(token, "ikun");
        console.log("payload", payload);

        return payload.exp > new Date().getTime() / 1000;
    } catch (error) {
        console.log("token 解析失败", error);
        return false;
    }
};
